

<!--
 * @Description: 直接荧光屏
 * 
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved. 
-->
<template>
  <div class="content">
      <div id="table-1">
				<div class="innertitle">
					1.本底值检测：(校准因子 <i>$C_{f}$ = <el-input style="width: 50px;" disabled v-model="form1.calibrationFactor"/></i>)设备未出束状态下
				</div>

				<table border="1" cellspacing="0" cellpadding="0" align="center" style="width: 100%;">
					<tr>
						<td style="width: 100px;">检测点位置</td>
						<td colspan="5">周围剂量当量率读数(
              <el-select  v-model="form1.readoutValueUnit"
                          placeholder="请选择"
                          style="width: 100px; display: inline-block"
                          class="inputborder"
                        >
                <el-option 
                  v-for="item in readoutList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>  
            )</td>
					</tr>
          <tr>
            <td><el-input v-model="form1.position_1"/></td>
            <td><el-input v-model="form1.readoutValue_1_1"/></td>
            <td><el-input v-model="form1.readoutValue_1_2"/></td>
            <td><el-input v-model="form1.readoutValue_1_3"/></td>
            <td><el-input v-model="form1.readoutValue_1_4"/></td>
            <td><el-input v-model="form1.readoutValue_1_5"/></td>
          </tr>
          <tr>
            <td><el-input v-model="form1.position_2"/></td>
            <td><el-input v-model="form1.readoutValue_2_1"/></td>
            <td><el-input v-model="form1.readoutValue_2_2"/></td>
            <td><el-input v-model="form1.readoutValue_2_3"/></td>
            <td><el-input v-model="form1.readoutValue_2_4"/></td>
            <td><el-input v-model="form1.readoutValue_2_5"/></td>
          </tr>
          <tr>
            <td><el-input v-model="form1.position_3"/></td>
            <td><el-input v-model="form1.readoutValue_3_1"/></td>
            <td><el-input v-model="form1.readoutValue_3_2"/></td>
            <td><el-input v-model="form1.readoutValue_3_3"/></td>
            <td><el-input v-model="form1.readoutValue_3_4"/></td>
            <td><el-input v-model="form1.readoutValue_3_5"/></td>
          </tr>
          <tr>
            <td><el-input v-model="form1.position_4"/></td>
            <td><el-input v-model="form1.readoutValue_4_1"/></td>
            <td><el-input v-model="form1.readoutValue_4_2"/></td>
            <td><el-input v-model="form1.readoutValue_4_3"/></td>
            <td><el-input v-model="form1.readoutValue_4_4"/></td>
            <td><el-input v-model="form1.readoutValue_4_5"/></td>
          </tr>
          <tr>
            <td>本底读出值</td>
            <td class="result">
              {{form1.backgroundReadoutValueMin}} ~ {{form1.backgroundReadoutValueMax}}
              ({{getLabel(readoutList, form1.readoutValueUnit)}})
            </td>
            <td>本底校准值</td>
            <td class="result">
              {{form1.backgroundRCalibrationValueMin}} ~ {{form1.backgroundRCalibrationValueMax}}(μSv/h)
            </td>
            <td>本底平均值</td>
            <td class="result">{{form1.backgroundAverage}}<i>μSv/h</i></td>
          </tr>
					
				</table>
			</div>

      <div id="table-2">
        <div class="innertitle">
					2.周围工作场所辐射防护测
				</div>
        <div class="tip-30">
          是否扣除本底值: <el-radio-group v-model="form2.deductBackground">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group> (响应时间修正系数: <el-input style="width: 30px;" v-model="form2.responseTimeCoefficient"/>);
            校准因子 <i>$C_{f}$ = <el-input style="width: 30px;" v-model="form2.calibrationFactor"/></i>,
            <el-checkbox v-model="form2.widthGreaterThan">
              OCT 准直宽度不小于 10mm 检测曝光条件: <el-input style="width: 30px;" v-model="form2.tubeVoltage"/>kV,
              <el-input style="width: 30px;" v-model="form2.tubeCurrent"/>
              <el-radio-group class="split-radio" v-model="form2.tubeCurrentUnit">
                <el-radio :label="0">mA</el-radio>
                <span class="split">/</span>
                <el-radio :label="1">mAs</el-radio>
              </el-radio-group>,
              <el-input style="width: 30px;" v-model="form2.exposureTime"/>s;
              照射野大小:<el-input style="width: 30px;" v-model="form2.irradiationFieldLength"/>cm X <el-input style="width: 30px;" v-model="form2.irradiationFieldWidth"/>cm,
              SID = <el-input style="width: 30px;" v-model="form2.sid"/> cm
            </el-checkbox>
            <el-checkbox v-model="form2.other">
              其它曝光条件:曝光模式: <el-select  v-model="form2.otherType"
                          placeholder="请选择"
                          style="width: 100px; display: inline-block"
                          class="inputborder"
                        >
                <el-option
                  v-for="item in otherTypeLists"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>; <el-input style="width: 30px;" v-model="form2.otherTubeVoltage"/>kV,
              <el-input style="width: 30px;" v-model="form2.otherTubeCurrent"/>
              <el-radio-group class="split-radio" v-model="form2.otherTubeCurrentUnit">
                <el-radio :label="1">mA</el-radio>
                <span class="split">/</span>
                <el-radio :label="2">mAs</el-radio>
              </el-radio-group>,
              <el-input style="width: 30px;" v-model="form2.otherExposureTime"/>s
            </el-checkbox>
        </div>

        <div style="margin: 10px 0;text-align: right;">
          <el-button type="primary" @click="openAddProtection">添加检测位</el-button>
        </div>

        <el-table
          :data="form2.detectionLocation"
          :header-cell-style="rowHeaderClass"
          :span-method="objectSpanMethod" 
          class="protection-table"
          style="width: 100%"
        >
          <el-table-column
            label="序号"
            align="center"
            prop="serialNumber">
            <template slot-scope="{row}">
              <el-input v-model="row.serialNumber"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="检测位置">
              <el-table-column align="center" prop="positionName" width="180">
                <template slot-scope="{row, $index}">
                  <el-input data-cusvalidate="text" v-model="row.positionName" @change="verifyName($event, row, $index)"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="positionDirection" width="180">
                <template slot-scope="{row}">
                  <el-input v-if="row.positionDirection" data-cusvalidate="text" v-model="row.positionDirection"></el-input>
                </template>
              </el-table-column>
            <!-- </template> -->
          </el-table-column>
          <el-table-column align="center">
            <template #header>
              周围剂量当量率(
                <el-select v-model="form2.readoutValueUnit"
                           placeholder="请选择"
                           style="width: 100px; display: inline-block"
                           class="inputborder"
                          >
                  <el-option
                    v-for="item in readoutList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"></el-option>
                </el-select>)
            </template>
            <el-table-column align="center" label="读出值">
              <el-table-column prop="readoutValue_1">
                <template slot-scope="{row}">
                  <el-input v-model="row.readoutValue_1"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="readoutValue_2">
                <template slot-scope="{row}">
                  <el-input v-model="row.readoutValue_2"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="readoutValue_3">
                <template slot-scope="{row}">
                  <el-input v-model="row.readoutValue_3"></el-input>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" prop="result">
            <template #header>
              检测结果<br/>(µSv/h)
            </template>
            <template slot-scope="{row}">
              <el-input v-model="row.result"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark">
            <template slot-scope="{row}">
              <el-input v-model="row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="{row, $index}">
              <el-button v-if="!row.initialization" type="primary" size="mini" @click="delDetectionLocation(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          title="添加检测位"
          :visible.sync="protectionShow"
          :close-on-click-modal="false"
          width="30%"
          append-to-body
          :destroy-on-close="true">
          <el-form ref="protectionForm" :model="form" label-width="80px">
            <!-- <el-form-item label="活动名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item> -->
            <el-form-item label="检测类型">
              <el-select v-model="form.type" placeholder="请选择检测类型">
                <el-option
                  v-for="item in dict.type.protection_condition"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="检测名称">
              <el-input v-model="form.positionName" placeholder="请输入检测位名称"></el-input>
            </el-form-item> -->
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="protectionShow = false">取 消</el-button>
            <el-button type="primary" @click="handleAddProtectionEvent">确 定</el-button>
          </span>
        </el-dialog>
      </div>

      <div id="table-3">
        <div class="innertitle" style="margin: 12px 0">
					3.检测点位示例图
          <el-button icon="el-icon-refresh" size="mini" style="float: right" @click="handleOpenDragCanvas()">设计平面图</el-button>
				</div>
        <div class="imageUpload">
          <imageUpload :limit="1" :isShowTip="false" v-model="form.ossId" @input="handleChangeImage"/>
        </div>

        <div class="tip-30">
          有关说明:<br/>
          1、本底校准值=本底读出值x校准因子;<br/>
          2、未扣除本底值情况下:检测结果=读出值平均值x校准因子，扣除本底值情况下: 检测结果=(读出值平均值-本底读出值)x校准因子x相应时间修正系数:<br/>
        </div>
      </div>

      <DragCanvas ref="dragCanvasRefs" @confirm="handleConfirmDrag" />
  </div>
</template>

<script>
import {getInfoById21, background, protection, saveInfo} from '@/api/testItem/item21'
import { listByIds } from "@/api/system/oss";
import DragCanvas from '../dragCanvas.vue'

export default {
  name: "testItem21",
  dicts: ['protection_condition'],
	components: { DragCanvas },
  data() {
    return {
      protectionShow: false,
      readoutList: [
        {
          id: 1,
          label: 'mSv/h',
          value: 1
        },
        {
          id: 2,
          label: 'μSv/h',
          value: 2
        },
      ],
      otherTypeLists: [
      {
          id: 1,
          label: '普通模式',
          value: 1
        },
        {
          id: 2,
          label: 'DBT',
          value: 2
        },
      ],
      // tab切换通用数据
			form: {},
			// 表单-1.本底值检测
			form1: {

			},
			// 表单-2、周围作场所辐射防护测
			form2: {

			},
      fileList: [],
      showImageUpload: false,
			itemsId: null,
      addTypeLists: [
        {
          type: 1,
          name: '点',
          positionDirections: ''
        },
        {
          type: 2,
          name: '车身',
          positionDirections: '(1),(2),(3)'
        },
        {
          type: 3,
          name: '窗',
          positionDirections: '上,中,下,左,右'
        },
        {
          type: 4,
          name: '门',
          positionDirections: '上,中,下,左,右'
        },
        {
          type: 5,
          name: '机房',
          positionDirections: '(1),(2),(3),(4)'
        },
      ]
    };
  },
  props: {
		// tab栏
    activeNameEquipment: {
			type: String,
      default: "0",
    },
		// 基本信息数据
    basicForm: {
			type: Object,
      default: () => {
				return {}
			},
    },
  },
  watch: {
    activeNameEquipment: {
      handler(val) {
		    let _this = this;
				this.$nextTick(()=>{
          // 02-直接荧光屏透视设备专用检测项目
          // 获取详情
          getInfoById21(this.basicForm.protectionDetectionVo.taskDetectionEquipmentResultId).then(response => {
            let {notHave, screenSpacing, itemsId, resultId, schematicImage, imageJson} = response.data
            this.form.imageJson = imageJson || '';
            this.itemsId =  response.data?.itemsId;
            // 1.本底值检测
            this.form1 =  response.data?.detectionBackgroundValue || {};
            // 2.周围工作场所辐射防护检测
            this.form2 =  response.data?.detectionProtection || {};
            this.$set(this.form2, 'detectionLocation', this.changeData(this.form2.detectionLocation))
            // 3.获取图片
            this.form.ossId = schematicImage
            this.showImageUpload = true

            // this.delData(31)

            // 绑定请求
            this.bindMethod()
            
          }).then().catch((response) => {
            // console.log("catch-->getInfoById06", response);
            this.$emit("loadingchange", true);
          });
          
				})
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    getLabel(data, value) {
      return data.find(item => item.value == value)?.label || ''
    },
		submitTestForm(index) {
			console.log("提交检测项", index);
			this.$emit("loadingchange", true); /* 说明绑定成功 */
      if (index === 'form') {
        this.form.itemsId = this.itemsId
      } else {
        this[`form${index}`].itemsId = this.itemsId;
      }
			switch (index) {
				// 1.DAS动态范围。DAS对比灵敏度 伪影
				case 1:
          background(this.form1).then((response) => {
						// this.$modal.msgSuccess("保存成功");
						response.data ? this.form1 = response.data : "";
						this.$emit("loadingchange", false);
					})
        	break;
        case 2:
          protection(this.form2).then((response) => {
						// this.$modal.msgSuccess("保存成功");
						response.data ? this.form2 = response.data : "";
            this.$set(this.form2, 'detectionLocation', this.changeData(this.form2.detectionLocation))
						this.$emit("loadingchange", false);
					})
        	break;
        case "form":
          // 其余信息
          let {ossId, itemsId, imageJson} = this.form;
          // let {resultId} = this.basicForm
          // return 
          saveInfo({ossId,itemsId,imageJson}).then((response) => {
            this.$emit("loadingchange", false);
          })
          break;
			}
		},
    changeData(detectionLocation) {
      return detectionLocation.reduce((prev, cur, index) => {
        let obj = prev.find(item => {
          return item.name == cur.positionName;
        })
        if (obj) {
          cur.rowspan = 0;
          detectionLocation[obj.rowIndex].rowspan += 1;
        }else {
          cur.rowspan = 1;
          cur.name = cur.positionName
          cur.rowIndex = index
        }
        if (!cur.positionDirection) {
          cur.colspan = 2;
        }
        prev.push(cur)
        return prev
      }, [])
      // this.$set(this.form2, 'detectionLocation', arr)
    },
    // 表格表头处理
    rowHeaderClass({row,column,rowIndex,columnIndex}){
      // console.log(row,column, rowIndex, columnIndex)
      if (rowIndex == 0 && columnIndex == 1) {
        this.$nextTick(() => {
          if (document.getElementsByClassName(column.id).length !== 0) {
            document.getElementsByClassName(column.id)[0].setAttribute('rowspan', 2)
          }
        })
      }
      let hiddenColum = {
        1: [0,1],
        2: [0,1,2]
      }
      Object.keys(hiddenColum).map(rowindex => {
        if (rowIndex == rowindex) {
          let allcolumIndex = hiddenColum[rowindex]
          if (allcolumIndex.indexOf(columnIndex) > -1) {
            this.$nextTick(() => {
              if (document.getElementsByClassName(column.id).length !== 0) {
                document.getElementsByClassName(column.id)[0].setAttribute('style', 'display: none;')
              }
            })
            // return { display: 'none' }
          }
        }
        return {}
      })
    },
    // 表格处理
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log( row, column, rowIndex, columnIndex )
      if (columnIndex === 2 && !row.positionDirection) {
        this.$nextTick(() => {
          let htmlCollection = document.getElementsByClassName(column.id);
          if (htmlCollection.length !== 0) {
            Array.from(htmlCollection).forEach(html => {
              if(html.getElementsByClassName('cell')[0].innerHTML === '') {
                html.setAttribute('style', 'display: none;')
              }
            })
          }
        })
      }
      if (columnIndex === 0 || columnIndex === 1 || columnIndex == 8) {
				if (row.rowspan) {
					return {
						rowspan: row.rowspan,
						colspan: columnIndex === 1 ? (row?.colspan || 1) : 1
					};
				} else {
					return {
						rowspan: 1,
						colspan: columnIndex === 1 ? (row?.colspan || 0) : 0
					};
				}
			}
    },
    openAddProtection() {
      this.resetForm('protectionForm')
      delete this.form.type
      this.protectionShow = true;
    },
    // 添加防护表格数据
    handleAddProtectionEvent() {
      let {type} = this.form
      let {detectionLocation} = this.form2
      let selectData = this.addTypeLists.find(t => t.type == type)
      let protectionLenth = this.form2.detectionLocation.length
      let data = selectData.positionDirections.split(',').reduce((pre, cur) => {
        const obj = {
          serialNumber: null,
          positionName: '',
          positionDirection: cur,
          readoutValue_1: null,
          readoutValue_2: null,
          readoutValue_3: null,
          result: null,
          remark: null,
          type,
          sort: protectionLenth + pre.length,
          isAdd: true,

        }
        pre.push(obj)
        return pre
      }, [])
      this.$set(this.form2, 'detectionLocation', [...detectionLocation, ...this.changeData(data)])
      this.bindMethod()
      this.submitTestForm(2)
      this.protectionShow = false
    },
    // 绑定方法
    bindMethod() {
      let itemsLength = 2;
      for (let index = 0; index < itemsLength; index++) {
        
        let tableInputs = document.getElementById(`table-${index + 1}`).getElementsByTagName("input");
        this.$nextTick(() => {
          Array.from(tableInputs).forEach(element => {
            this.bind(element, () => {
              this.submitTestForm(index + 1)
            })
          });
        })
      }
    },
    handleOpenDragCanvas() {
			this.$refs.dragCanvasRefs.openDialog({
				imageJson: this.form.imageJson
			})
		},
    handleConfirmDrag(data) {
      this.form = {
        ...this.form,
        'ossId': data.ossId,
        'imageJson': data.imageJson
      }
      this.submitTestForm('form')
		},
    handleChangeImage(val) {
      this.submitTestForm('form')
    },
    // 删除表格
    delDetectionLocation(row, index) {
      console.log('del table: ' + row, index)
      let delLength = this.addTypeLists.find(list => list.type == row.type)?.positionDirections.split(',').length || 0
      this.form2.detectionLocation.splice(index, delLength)
      this.submitTestForm(2)
    },
    // 验证名称

    verifyName(event, row, index) {
      if (this.findName(event)) {
        let findobj = {...this.form2.detectionLocation[index]}
        findobj.positionName = ''
        this.$set(this.form2.detectionLocation, index, findobj)
        this.$message({
          showClose: true,
          message: '检测名称相同,请重新输入',
          type: 'warning'
        });
        return
      }
      let length = this.addTypeLists.find(list => list.type == row.type)?.positionDirections.split(',').length || 0
      for(let i = 0; i < length; i++){
        this.form2.detectionLocation[index + i].positionName = event
      }
    },
    // 查找名字
    findName(name) {
      return this.form2.detectionLocation.filter(item => item.positionName == name)?.length > 1 || false
    },
    // 测试用  根据sort删除
    delData(sort) {
      let index = this.addTypeLists.findIndex(list => list.sort == sort)
      this.form2.detectionLocation.splice(index, 1)
      this.submitTestForm(2)
    }
  },
};
</script>

<style lang="scss" scoped>
@import '../content.scss';
.protection-table {
  ::v-deep .el-input{
    width: 100%;
  }
}
</style>